Telegram Service
This document provides comprehensive documentation for the TelegramService component that powers the Telegram bot functionality and user interaction within the SuperSet placement notification system. It explains how TelegramService integrates with the python-telegram-bot library, handles command processing, manages users, and participates in the broader notification ecosystem. It also covers the bot server implementation, message handling patterns, subscription management, and security considerations.
The TelegramService resides in the services layer and collaborates with the bot server, database service, and notification service. The configuration module centralizes environment-driven settings, and the main entry point wires the dependency injection for the Telegram bot server.
Diagram sources
Section sources
TelegramService: Implements the Telegram channel for notifications, including message formatting, long message splitting, and user broadcasting.
TelegramClient: Low-level client for Telegram Bot API interactions, including retries, rate-limit handling, and connection testing.
BotServer: Asynchronous Telegram bot server that registers command handlers and manages lifecycle.
AdminTelegramService: Provides admin-only commands and authentication enforcement.
DatabaseService: User management and persistence for subscriptions.
NotificationService: Aggregates channels and routes notifications to Telegram and other channels.
Section sources
The TelegramService sits at the intersection of user commands, message formatting, and outbound notifications. It relies on TelegramClient for API interactions and integrates with DatabaseService for user management and NotificationService for broadcast orchestration.
Diagram sources
TelegramService#
TelegramService encapsulates Telegram-specific functionality:
Channel identity and connection testing
Message sending to default channel, specific users, and broadcasting to all active users
Message formatting helpers for MarkdownV2 and HTML
Long message splitting and chunked delivery
Fallback to plain text on formatting failures
Key responsibilities:
Implementing the INotificationChannel protocol for Telegram
Integrating with TelegramClient for API calls
Leveraging DatabaseService for user lookups during broadcasts
Providing convenience methods for HTML-formatted messages
Diagram sources
Section sources
TelegramClient#
TelegramClient provides low-level API interactions:
Validates presence of bot token and target chat ID
Sends messages with parse modes and disables web page preview
Implements retry logic with exponential backoff
Handles Telegram’s rate limiting (HTTP 429) with Retry-After header
Tests authentication via getMe endpoint
Diagram sources
Section sources
BotServer#
BotServer initializes and runs the Telegram bot:
Dependency injection for services (DatabaseService, NotificationService, AdminTelegramService, PlacementStatsCalculatorService)
Registers command handlers for user-facing commands (/start, /help, /stop, /status, /stats, /noticestats, /userstats, /web)
Registers admin commands via AdminTelegramService
Starts asynchronous polling with drop_pending_updates
Supports daemon mode and graceful shutdown
Diagram sources
Section sources
AdminTelegramService#
AdminTelegramService enforces admin-only commands:
Authenticates commands by comparing chat ID with configured admin chat ID
Provides commands: users (list users), broadcast (broadcast or targeted send), scrape (force update), logs (view logs), kill (stop scheduler)
Uses TelegramService for broadcasting and message sending
Uses DatabaseService for user and statistics queries
Diagram sources
Section sources
NotificationService Integration#
NotificationService aggregates channels and routes notifications:
Adds TelegramService as a channel
Broadcasts to Telegram via TelegramService.broadcast_to_all_users
Sends unsent notices to Telegram and marks them sent upon success
Diagram sources
Section sources
DatabaseService User Management#
DatabaseService handles user lifecycle:
Registration on /start: add_user with activation
Deactivation on /stop: deactivate_user
Status checks: get_user_by_id and get_active_users
Admin user listing: get_all_users
Diagram sources
Section sources
TelegramService depends on TelegramClient for API calls and DatabaseService for user data during broadcasts.
BotServer composes services via dependency injection and registers command handlers.
AdminTelegramService depends on DatabaseService and TelegramService for admin operations.
NotificationService depends on TelegramService for channel routing and DatabaseService for unsent notices.
Diagram sources
Section sources
Rate limiting: TelegramClient respects Retry-After headers and applies exponential backoff.
Broadcast throttling: TelegramService adds small delays between sends to avoid rate limits.
Long message handling: TelegramService splits messages into chunks and sends sequentially with short sleeps.
Efficient user queries: DatabaseService provides active user lists for targeted broadcasts.
[No sources needed since this section provides general guidance]
Common issues and resolutions:
Telegram bot token or chat ID not configured: TelegramService and TelegramClient return False and log warnings.
Rate limiting: TelegramClient handles 429 with Retry-After; consider reducing broadcast concurrency.
Formatting failures: TelegramService falls back to plain text when parse_mode fails.
Admin command unauthorized: AdminTelegramService checks chat ID and rejects non-admins.
Logging: Use safe_print and centralized logging via setup_logging.
Section sources
The TelegramService provides a robust, modular foundation for Telegram bot functionality within the notification system. It integrates cleanly with the broader architecture, handles user onboarding and subscription management, and ensures reliable message delivery with built-in resilience against API limitations. AdminTelegramService enhances operational capabilities, while NotificationService and DatabaseService round out the ecosystem for scalable, production-grade notifications.
[No sources needed since this section summarizes without analyzing specific files]
Configuration and Environment#
TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID are required for TelegramService and BotServer.
Daemon mode and logging levels are configurable via Settings.
Section sources
Command Reference#
User commands: /start, /help, /stop, /status, /stats, /noticestats, /userstats, /web
Admin commands: /users, /boo, /fu, /logs, /kill
Section sources
Security Considerations#
Bot token and admin chat ID are validated and never logged.
Admin commands require exact chat ID match.
TelegramClient avoids exposing tokens in logs.
Section sources